//
//  NSData+BZEncrypt.m
//  BZFoundation
//
//  Created by 郭艺伟 on 2017/9/30.
//  Copyright © 2017年 郭艺伟. All rights reserved.
//

#import "NSData+BZEncrypt.h"
#include <CommonCrypto/CommonDigest.h>
@implementation NSData (BZEncrypt)
+ (NSString *)bz_stringFromDigest:(uint8_t *)digest length:(int)length {
    NSMutableString *ms = [[NSMutableString alloc] initWithCapacity:length * 2];
    for (int i = 0; i < length; i++) {
        [ms appendFormat: @"%02x", (int)digest[i]];
    }
    return [ms copy];
}

- (NSString *)bz_md2String {
    uint8_t digest[CC_MD2_DIGEST_LENGTH];
    CC_MD2(self.bytes, (CC_LONG)self.length, digest);
    return [[self class] bz_stringFromDigest:digest length:CC_MD2_DIGEST_LENGTH];
}

- (NSString *)bz_md4String {
    uint8_t digest[CC_MD4_DIGEST_LENGTH];
    CC_MD4(self.bytes, (CC_LONG)self.length, digest);
    return [[self class] bz_stringFromDigest:digest length:CC_MD4_DIGEST_LENGTH];
}

- (NSString *)bz_md5String {
    uint8_t digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(self.bytes, (CC_LONG)self.length, digest);
    return [[self class] bz_stringFromDigest:digest length:CC_MD5_DIGEST_LENGTH];
}

- (NSString *)bz_sha1String {
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(self.bytes, (CC_LONG)self.length, digest);
    return [[self class] bz_stringFromDigest:digest length:CC_SHA1_DIGEST_LENGTH];
}

- (NSString *)bz_sha224String {
    uint8_t digest[CC_SHA224_DIGEST_LENGTH];
    CC_SHA224(self.bytes, (CC_LONG)self.length, digest);
    return [[self class] bz_stringFromDigest:digest length:CC_SHA224_DIGEST_LENGTH];
}

- (NSString *)bz_sha256String {
    uint8_t digest[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(self.bytes, (CC_LONG)self.length, digest);
    return [[self class] bz_stringFromDigest:digest length:CC_SHA256_DIGEST_LENGTH];
}

- (NSString *)bz_sha384String {
    uint8_t digest[CC_SHA384_DIGEST_LENGTH];
    CC_SHA384(self.bytes, (CC_LONG)self.length, digest);
    return [[self class] bz_stringFromDigest:digest length:CC_SHA384_DIGEST_LENGTH];
}

- (NSString *)bz_sha512String {
    uint8_t digest[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512(self.bytes, (CC_LONG)self.length, digest);
    return [[self class] bz_stringFromDigest:digest length:CC_SHA512_DIGEST_LENGTH];
}

- (NSString *)bz_hexadedimalString {
    NSMutableString *string = [NSMutableString string];
    const unsigned char *bytes = [self bytes];
    NSUInteger length = [self length];
    for (NSUInteger i = 0; i < length; i++) {
        [string appendFormat:@"%02x", bytes[i]];
    }
    return string;
}

@end
